package com.starbaba.loantopic.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.stereotype.Component;

import com.base.common.database.BaseDao;
import com.base.common.database.DaoHelper;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.base.common.util.StringUtils;
import com.jumai.server.qiniu.QiniuUploadUtils;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.loantopic.model.LoanTopicModel;
import com.starbaba.loantopic.model.LoanTopicProductModel;
import com.starbaba.loantopic.service.LoanTopicService;
import com.starbaba.model.dictionary.Constant;

/**
 * 贷款产品管理
 * 
 * @version 1.0
 */
@Component
public class LoanTopicServiceImpl implements LoanTopicService {

	@SuppressWarnings("deprecation")
	private static BaseDao dao = new BaseDao(Constant.POOL_LIFE);

	@Override
	@SuppressWarnings("rawtypes")
	public List<LoanTopicModel> getDataList(int iDisplayStart, int iDisplayLength, PageResponse pageResponse,
			Map<String, Object> paramsMap) {

		String topicId = (String) paramsMap.get("topicId");
		String topicName = (String) paramsMap.get("topicName");
		String type = (String) paramsMap.get("type");
		String status = (String) paramsMap.get("status");
		String product_id = (String) paramsMap.get("product_id");

		String sql = "select a.id,a.name, a.type, a.url,a.operator, a.status, a.createtime from loan_topic_info a ";
		String selectSql = "";
		if (!StringUtils.isEmpty(product_id)) {
			sql = sql + " ,loan_topic_product b ";
		}
		sql = sql + " where a.status in (0,1) ";
		if (!StringUtils.isEmpty(product_id)) {
			sql = sql + " and a.id = b.topic_id  and b.product_id = " + product_id + " ";
		}

		if (!StringUtils.isEmpty(topicId)) {
			selectSql += " and a.id = '" + topicId + "'";
		}
		if (!StringUtils.isEmpty(topicName)) {
			selectSql += " and a.name like '" + topicName + "%'";
		}
		if (!StringUtils.isEmpty(status)) {
			selectSql += " and a.status = '" + status + "'";
		}
		if (!StringUtils.isEmpty(type)) {
			selectSql += " and a.type = '" + type + "'";
		}
		sql += selectSql;
		sql += " order by a.createtime desc limit " + iDisplayStart + " , " + iDisplayLength;

		LogService.info("专题SQL :" + sql );
		
		String countSql = "select count(1) from loan_topic_info a ";
		if (!StringUtils.isEmpty(product_id)) {
			countSql = countSql + " ,loan_topic_product b where a.id = b.topic_id  and b.product_id =" + product_id + " ";
		}else{
			countSql = countSql + " where 1=1 ";
		}
		countSql = countSql + selectSql;
		List<LoanTopicModel> list = null;
		try {
			int count = dao.getInt(countSql);
			list = dao.list(sql, LoanTopicModel.class, new Object[] {});
			pageResponse.setITotalRecords(count);
			pageResponse.setITotalDisplayRecords(count);
		} catch (AppException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public void save(Map<String, Object> paramsMap, LoanTopicModel bean) {
		LoanTopicModel model = setValue(bean);
		try {
			Long topicId = dao.addReturnGeneratedKey(model); // 新增专题
			if (topicId != null) {
				addTopicProduct(dao, paramsMap, topicId);
			}
		} catch (AppException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 增加专题产品
	 * 
	 * @param paramsMap
	 * @param topicId
	 * @throws AppException
	 */
	private void addTopicProduct(BaseDao dao, Map<String, Object> paramsMap, Long topicId) throws AppException {

		String productData = (String) paramsMap.get("product");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String currDate = format.format(new Date());

		if (!StringUtils.isEmpty(productData)) {
			String[] productArr = productData.split(";");
			for (int i = 0; i < productArr.length; i++) {
				String[] data = productArr[i].split(",");
				LoanTopicProductModel model = new LoanTopicProductModel();
				for (int j = 0; j < data.length; j++) {
					model.setTopic_id(topicId);
					model.setPosition(Integer.parseInt(data[0]));

					String ad_image = data[2]; // 广告图片
					if (!StringUtils.isEmpty(ad_image)) {
						model.setAd_image(ad_image);
					}

					String activity_url = data[3]; // 活动链接
					if (!StringUtils.isEmpty(activity_url)) {
						model.setActivity_url(activity_url);
					}

					model.setProduct_id(Integer.parseInt(data[4]));
					if (data.length > 5) {
						model.setProduct_desc(StringUtils.isEmpty(data[5]) ? "" : data[5]);
					}
					if (data.length > 6) {
						model.setTag(StringUtils.isEmpty(data[6]) ? "" : data[6]);
					}
					model.setCtime(currDate);
					model.setUtime(currDate);
				}
				dao.add(model);
			}
		}
	}

	public LoanTopicModel setValue(LoanTopicModel bean) {

		LoanTopicModel model = null;
		try {
			model = new LoanTopicModel();
			String image1 = null;
			String image2 = null;
			String thumbnail = null;
			File imageFile1 = bean.getImg1();
			File imageFile2 = bean.getImg2();
			File thumbnailFile = bean.getImg3();
			if (imageFile1 != null) {
				image1 = uploadToQiniu(imageFile1);
				model.setImage1(image1);
			}
			if (imageFile2 != null) {
				image2 = uploadToQiniu(imageFile2);
				model.setImage2(image2);
			}
			if (thumbnailFile != null) {
				thumbnail = uploadToQiniu(thumbnailFile);
				model.setThumbnail(thumbnail);
			}

			if (!StringUtils.isEmpty(bean.getName())) {
				model.setName(bean.getName());
			}
			if (!StringUtils.isEmpty(bean.getUrl())) {
				model.setUrl(bean.getUrl());
			}
			if (!StringUtils.isEmpty(bean.getTopic_desc())) {
				model.setTopic_desc(bean.getTopic_desc());
			}
			if (bean.getStatus() != null) {
				model.setStatus(bean.getStatus());
			}
			if (!StringUtils.isEmpty(bean.getOperator())) {
				model.setOperator(bean.getOperator());
			}
			if (!StringUtils.isEmpty(bean.getType())) {
				model.setType(bean.getType());
			}
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date = format.format(new Date());
			model.setCreatetime(date);
			model.setUpdatetime(date);
			model.setOperator(bean.getOperator());
			model.setBackground_color(bean.getBackground_color());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return model;
	}

	public String uploadToQiniu(File srcFile) {
		String iconUrl = null;
		if (srcFile.isDirectory()) {
			return iconUrl;
		} else {
			try {
				FileInputStream in = new FileInputStream(srcFile);
				// Zone为七牛机房所在地，根据源所在机房配置
				Configuration config = new Configuration(Zone.zone0());
				iconUrl = QiniuUploadUtils.updateImg("loan", in, null, config);
				in.close();
			} catch (Exception e) {
				e.printStackTrace();
				LogService.error(e);
			}
		}
		return iconUrl;
	}

	@Override
	public void update(Map<String, Object> paramsMap, LoanTopicModel bean, Long topicId) throws Exception {

		LoanTopicModel model = setValue(bean);
		try {
			DaoHelper.startTransaction();
			model.setId(topicId);
			int result = dao.update(model, new String[] { "id" }); // 修改专题信息
			if (result == 1) {
				// 查询专题对应的产品ID
				Map<String, Integer> prdMap = new HashMap<String, Integer>();
				LoanTopicProductModel topicProduct = new LoanTopicProductModel();
				topicProduct.setTopic_id(topicId);
				List<LoanTopicProductModel> productList = dao.list(topicProduct, new String[] { "topic_id" });
				if (productList != null && productList.size() > 0) {
					for (LoanTopicProductModel prod : productList) {
						prdMap.put(String.valueOf(prod.getProduct_id()), prod.getProduct_id());
					}
				}

				List<LoanTopicProductModel> prdList = new ArrayList<LoanTopicProductModel>();

				String productData = (String) paramsMap.get("product");
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String currDate = format.format(new Date());

				if (!StringUtils.isEmpty(productData)) {
					String[] productArr = productData.split(";");
					for (int i = 0; i < productArr.length; i++) {
						String[] data = productArr[i].split(",");
						LoanTopicProductModel productModel = new LoanTopicProductModel();

						for (int j = 0; j < data.length; j++) {

							productModel.setTopic_id(topicId);
							productModel.setPosition(Integer.parseInt(StringUtils.trim(data[0])));

							String ad_image = data[2]; // 广告图片
							if (!StringUtils.isEmpty(ad_image)) {
								productModel.setAd_image(ad_image);
							}

							String activity_url = data[3]; // 活动链接
							if (!StringUtils.isEmpty(activity_url)) {
								productModel.setActivity_url(activity_url);
							}

							productModel.setProduct_id(Integer.parseInt(StringUtils.trim(data[4])));
							if (data.length > 6) {
								productModel.setProduct_desc(StringUtils.isEmpty(data[6]) ? "" : data[6]);
							}
							if (data.length > 7) {
								productModel.setTag(StringUtils.isEmpty(data[7]) ? "" : data[7]);
							}
							productModel.setCtime(currDate);
							productModel.setUtime(currDate);

							if (data.length > 8) {
								String online_time = data[8];
								if (StringUtils.isEmpty(online_time)) {
									productModel.setOnline_time(null);
								} else {
									productModel.setOnline_time(online_time);
								}
							}

							if (data.length > 9) {
								String offline_time = data[9];
								if (StringUtils.isEmpty(offline_time)) {
									productModel.setOffline_time(null);
								} else {
									productModel.setOffline_time(offline_time);
								}
							}

							if (data.length > 10) {
								String every_day_online_time = data[10];
								if (StringUtils.isEmpty(every_day_online_time)) {
									productModel.setEvery_day_online_time(null);
								} else {
									productModel.setEvery_day_online_time(every_day_online_time);
								}
							}

							if (data.length > 11) {
								String every_day_offline_time = data[11];
								if (StringUtils.isEmpty(every_day_offline_time)) {
									productModel.setEvery_day_offline_time(null);
								} else {
									productModel.setEvery_day_offline_time(every_day_offline_time);
								}
							}

						}
						prdList.add(productModel);
					}
				}

				List<Integer> tempList = new ArrayList<Integer>();

				for (Iterator<LoanTopicProductModel> it = prdList.iterator(); it.hasNext();) {

					LoanTopicProductModel product = it.next();

					Integer productId = product.getProduct_id();

					if (tempList.contains(productId)) {
						it.remove();
					} else {
						tempList.add(productId);
					}
				}

				for (LoanTopicProductModel productModel : prdList) {
					String prdkey = String.valueOf(productModel.getProduct_id());

					if (prdMap.containsKey(prdkey)) { // 判断产品是否存在，如果存在，则更新
					// String sql =
					// "update loan_topic_product set ad_image = ?, activity_url = ?, product_id = ?, "
					// +
					// "product_desc = ?, tag = ? , position = ?, utime = ? where topic_id = ? and product_id = ?";
					// dao.update(sql, new Object[] {
					// StringUtils.isEmpty(productModel.getAd_image()) ? "" :
					// productModel.getAd_image(),
					// StringUtils.isEmpty(productModel.getActivity_url()) ? ""
					// : productModel.getActivity_url(),
					// productModel.getProduct_id() == null ? "" :
					// productModel.getProduct_id(),
					// StringUtils.isEmpty(productModel.getProduct_desc()) ? ""
					// : productModel.getProduct_desc(),
					// StringUtils.isEmpty(productModel.getTag()) ? "" :
					// productModel.getTag(),
					// productModel.getPosition() == null ? "" :
					// productModel.getPosition(), currDate, topicId,
					// prdkey });
						dao.update(productModel, "topic_id", "product_id");

						if (StringUtils.isEmpty(productModel.getOnline_time())) {
							dao.update(
									"UPDATE `loan_topic_product` SET `online_time` = null WHERE `topic_id`  = ? AND `product_id` = ?",
									topicId, prdkey);
						}

						if (StringUtils.isEmpty(productModel.getOffline_time())) {
							dao.update(
									"UPDATE `loan_topic_product` SET `offline_time` = null WHERE `topic_id`  = ? AND `product_id` = ?",
									topicId, prdkey);
						}

						if (StringUtils.isEmpty(productModel.getEvery_day_online_time())) {
							dao.update(
									"UPDATE `loan_topic_product` SET `every_day_online_time` = null WHERE `topic_id`  = ? AND `product_id` = ?",
									topicId, prdkey);
						}

						if (StringUtils.isEmpty(productModel.getEvery_day_offline_time())) {
							dao.update(
									"UPDATE `loan_topic_product` SET `every_day_offline_time` = null WHERE `topic_id`  = ? AND `product_id` = ?",
									topicId, prdkey);
						}

					} else {
						dao.add(productModel); // 不存在则新增
					}
					prdMap.remove(prdkey);
				}

				// clean表单列表不存在的产品
				Iterator<Map.Entry<String, Integer>> it = prdMap.entrySet().iterator();
				while (it.hasNext()) {
					Entry<String, Integer> entry = it.next();
					dao.delete("delete from loan_topic_product where topic_id = ? and product_id = ?", topicId,
							entry.getValue());
				}
			}
			DaoHelper.commitTransaction();
		} catch (Exception e) {
			DaoHelper.rollbackTransaction();
			LogService.error(e);
		}
	}
}
